<?php


namespace plugins\wechat\controller;

use api\crm\model\ActivitySignModel;
use api\crm\model\WechatUserModel;
use api\crm\model\WechatUserPointsLogModel;
use app\admin\model\AuthAppidModel;
use app\admin\model\MemberCardInfoModel;
use app\admin\model\OrderInfoModel;
use app\admin\model\WechatSettingModel;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Text;
use EasyWeChat\OfficialAccount\Application;
use plugins\wechat\model\GetCardLogModel;
use plugins\wechat\model\WechatReplyModel;
use plugins\wechat\services\SystemConfigService;
use plugins\wechat\WechatPlugin;
use think\Controller;
use EasyWeChat\Kernel\Messages\Transfer;
use think\Db;

class WechatController extends Controller
{
    public function index()
    {
        $plugin = new  WechatPlugin();
        $config = $plugin->config();

        $aa = SystemConfigService::get_web_config();
        var_dump($aa);
    }

    public function notify()
    {
        $plugin = new  WechatPlugin();
        $id = input('id');
        $setting = WechatSettingModel::where('company_id', $id)->find();
        $config = unserialize($setting['setting']);
        $web_config = [
            'app_id' => $config['appid'],
            'secret' => $config['secret'],
            'mch_id' => $config['mch_id'],
            'key' => $config['key'],
            'cert_path' => CMF_ROOT . 'public/plugins/wechat/cert/' . $config['cert_path'], // XXX: 绝对路径！！！！
            'key_path' => CMF_ROOT . 'public/plugins/wechat/cert/' . $config['key_path'],      // XXX: 绝对路径！！！！
            'notify_url' => $config['notify_url'],     // 你也可以在下单时单独设置来想覆盖它
            'log' => [
                'level' => 'debug',
                'file' => CMF_ROOT . 'public/plugins/wechat/logs/wechat.log',
            ],
        ];
        $app = Factory::payment($web_config);
        $response = $app->handlePaidNotify(function ($message, $fail) {
            $order_sn = $message['out_trade_no'];
            $array = explode('_', $order_sn);
            $type = $array[0];
            switch ($type) {
                case 'ACTIVITY':
                    $order = ActivitySignModel::with('activity_info')->where('order_sn', $order_sn)->find();
                    if (!$order || $order['status'] == 1) {
                        return true;
                    }
                    if ($message['return_code'] === 'SUCCESS') {
                        if ($message['result_code'] === 'SUCCESS') {
                            $activity = $order['activity_info'];
                            $wechat_user = WechatUserModel::get($order['user_id']);
                            if ($activity['give_points'] > 0) {
                                $log = new WechatUserPointsLogModel([
                                    'user_id' => $order['user_id'],
                                    'change_points' => $activity['give_points'],
                                    'before_points' => $wechat_user['points'],
                                    'after_points' => $activity['give_points'] + $wechat_user['points'],
                                    'remark' => '报名' . $activity['title'] . '获得' . $activity['give_points'] . '积分'
                                ]);
                                $log->save();
                                $wechat_user->points = ['inc', $activity['give_points']];
                                $wechat_user->save();

                                // 变更 会员卡 积分
                                $card_info = \app\admin\model\GetCardLogModel::where('openid', $wechat_user['openid'])->find();
                                $obj = new WechatPlugin();

                                $obj->update_card_info([
                                    'company_id' => $wechat_user['company_id'],
                                    'user_id' => $wechat_user['id'],
                                    'cardId' => $card_info['card_id'],
                                    'code' => $card_info['user_card_code'],
                                    'bonus' => $activity['give_points'] + $wechat_user['points'],
                                ]);

                            }
                            $order->money = $message['total_fee'] / 100;
                            $order->points = $activity['give_points'];
                            $order->pay_time = time();
                            $order->status = 1;
                        } else {
                            $order->status = 3;
                        }
                        $order->save();
                        return true;
                    } else {
                        return $fail('通信失败，请稍后再通知我');
                    }
                    break;
                case 'PAY':
                    $order = OrderInfoModel::where(['pay_sn' => $order_sn])->find();
                    if (!$order || $order['pay_status'] > 1) {
                        return true;
                    }
                    if ($message['return_code'] === 'SUCCESS') {
                        if ($message['result_code'] === 'SUCCESS') {
                            $wechat_user = WechatUserModel::get($order['user_id']);
                            $user_points = $wechat_user['points'];
//                            if ($order['gift_points'] > 0) {
//                                $add_log = new WechatUserPointsLogModel([
//                                    'user_id' => $order['user_id'],
//                                    'change_points' => $order['gift_points'],
//                                    'before_points' => $user_points,
//                                    'after_points' => $user_points + $order['gift_points'],
//                                    'order_sn' => $order_sn,
//                                    'remark' => '订单号' . $order_sn . '赠送' . $order['gift_points'] . '积分'
//                                ]);
//                                $add_log->save();
//                                $wechat_user->points = ['inc', $order['gift_points']];
//                                $wechat_user->save();
//                                $user_points = $user_points + $order['gift_points'];
//                            }
                            if ($order['pay_points'] > 0) {
                                $log = new WechatUserPointsLogModel([
                                    'user_id' => $order['user_id'],
                                    'change_points' => $order['pay_points'],
                                    'before_points' => $user_points,
                                    'after_points' => $user_points - $order['pay_points'],
                                    'order_sn' => $order_sn,
                                    'remark' => '订单号' . $order_sn . '消耗' . $order['pay_points'] . '积分'
                                ]);
                                $log->save();
                                $wechat_user->points = ['dec', $order['pay_points']];
                                $wechat_user->save();

                                // 变更 会员卡 积分
                                $card_info = \app\admin\model\GetCardLogModel::where('openid', $wechat_user['openid'])->find();
                                $obj = new WechatPlugin();

                                $obj->update_card_info([
                                    'company_id' => $wechat_user['company_id'],
                                    'user_id' => $wechat_user['id'],
                                    'cardId' => $card_info['card_id'],
                                    'code' => $card_info['user_card_code'],
                                    'bonus' => $user_points - $order['pay_points'],
                                ]);

                                // 当有推荐人  推荐人拿奖励积分
                                if (!empty($wechat_user['parent_id'])) {
                                    // 推荐用户购买产品得积分比例
                                    $user_buy = Db::name('option')->where('option_name', 'user_buy' . $wechat_user['company_id'])->value('option_value');
                                    if ($user_buy > 0) {
                                        $giving_points = round($order['pay_points'] * $user_buy, 2);

                                        $find = WechatUserModel::where('id', $wechat_user['parent_id'])->find();

                                        $parent = new WechatUserModel;
                                        $parent::where('id', $wechat_user['parent_id'])->setInc('points', $giving_points);

                                        // 积分日志
                                        $log = new WechatUserPointsLogModel;
                                        $log->data([
                                            'user_id' => $wechat_user['parent_id'],
                                            'change_points' => $giving_points,
                                            'before_points' => $find['points'],
                                            'after_points' => $find['points'] + $giving_points,
                                            'create_time' => time(),
                                            'update_time' => time(),
                                            'remark' => '您分享的用户昵称为：' . $wechat_user['nickname'] . '，购买了产品，您成功获得' . $giving_points . '积分',
                                        ]);
                                        $log->save();
                                        // 变更 会员卡 积分
                                        $cardInfo = \api\crm\model\GetCardLogModel::where('openid', $find['openid'])
                                            ->distinct(true)
                                            ->field('card_id,user_card_code')->select();

                                        $obj = new WechatPlugin();
                                        if ($cardInfo) {
                                            foreach ($cardInfo as $k => $v) {
                                                $obj->update_card_info([
                                                    'company_id' => $find['company_id'],
                                                    'user_id' => $find['id'],
                                                    'cardId' => $v['card_id'],
                                                    'code' => $v['user_card_code'],
                                                    'bonus' => $find['points'] + $giving_points
                                                ]);
                                            }
                                        }

                                    }
                                }


                            }
                            $order->money_paid = $message['total_fee'] / 100;
                            $order->pay_status = 2;
                            $order->pay_time = time();
                            if ($order['card_code']) {
                                $param['company_id'] = $order['company_id'];
                                $param['code'] = $order['card_code'];
                                hook('consume_coupon', $param);
                                GetCardLogModel::where(['card_id' => $order['card_id'], 'user_card_code' => $order['card_code']])->update(['status' => 1]);
                            }
                        } else {
                            $order->pay_status = 4;
                        }
                        $order->save();
                        return true;
                    } else {
                        return $fail('通信失败，请稍后再通知我');
                    }
                    break;
                default:
                    break;
            }
        });
        return $response;
//        $response->send(); // return $response;
    }

    public function oauth_callback()
    {
        $id = input('id');
        $setting = WechatSettingModel::where('company_id', $id)->find();
        $plugin = new  WechatPlugin();
        $config = unserialize($setting['setting']);
        $options = [
            /**
             * 账号基本信息，请从微信公众平台/开放平台获取
             */
            'app_id' => $config['appid'],         // AppID
            'secret' => $config['secret'],     // AppSecret
            'token' => $config['token'],          // Token
            'aes_key' => $config['EncodingAESKey'],                    // EncodingAESKey，兼容与安全模式下请一定要填写！！！

            /**
             * 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
             * 使用自定义类名时，构造函数将会接收一个 `EasyWeChat\Kernel\Http\Response` 实例
             */
            'response_type' => 'array',

            /**
             * 日志配置
             *
             * level: 日志级别, 可选为：
             *         debug/info/notice/warning/error/critical/alert/emergency
             * path：日志文件位置(绝对路径!!!)，要求可写权限
             */
            'log' => [
                'default' => 'dev', // 默认使用的 channel，生产环境可以改为下面的 prod
                'channels' => [
                    // 测试环境
                    'dev' => [
                        'driver' => 'single',
                        'path' => CMF_ROOT . 'public/plugins/wechat/logs/wechat.log',
                        'level' => 'debug',
                    ],
                    // 生产环境
                    'prod' => [
                        'driver' => 'daily',
                        'path' => CMF_ROOT . 'public/plugins/wechat/logs/wechat.log',
                        'level' => 'info',
                    ],
                ],
            ],

            /**
             * 接口请求相关配置，超时时间等，具体可用参数请参考：
             * http://docs.guzzlephp.org/en/stable/request-config.html
             *
             * - retries: 重试次数，默认 1，指定当 http 请求失败时重试的次数。
             * - retry_delay: 重试延迟间隔（单位：ms），默认 500
             * - log_template: 指定 HTTP 日志模板，请参考：https://github.com/guzzle/guzzle/blob/master/src/MessageFormatter.php
             */
            'http' => [
                'max_retries' => 1,
                'retry_delay' => 500,
                'timeout' => 5.0,
                // 'base_uri' => 'https://api.weixin.qq.com/', // 如果你在国外想要覆盖默认的 url 的时候才使用，根据不同的模块配置不同的 uri
            ],

            /**
             * OAuth 配置
             *
             * scopes：公众平台（snsapi_userinfo / snsapi_base），开放平台：snsapi_login
             * callback：OAuth授权完成后的回调页地址
             */
            'oauth' => [
                'scopes' => ['snsapi_userinfo'],
                'callback' => '/plugin/wechat/wechat/oauth_callback',
            ],
        ];
        $app = new Application($options);
        $server = $app->server;

        self::hook($server);
        $response = $server->serve();
        $response->send(); //微信回调设置
    }

    public function auth_oauth_callback()
    {
        $appid = input('appid');
        $info = AuthAppidModel::where(['appid' => $appid])->find();
        $plugin = new  WechatPlugin();
        $openPlatform = $plugin->getOpenPlatForm();
        if ($appid == 'wx570bc396a51b8ff8') {
            return $this->releaseToNetWork($openPlatform, $appid);
        }
        $officialAccount = $openPlatform->officialAccount($info['appid']);
        $server = $officialAccount->server;

        self::auth_hook($server);
        $response = $server->serve();
        $response->send(); //微信回调设置
    }

    public function web_wechat_config()
    {
        $plugin = new  WechatPlugin();
        $config = $plugin->config();
        $web_config = [
            'app_id' => $config['web_appid'],
            'secret' => $config['web_secret'],
            'response_type' => 'array',
            'oauth' => [
                'scopes' => ['snsapi_userinfo'],
                'callback' => '/plugin/wechat/wechat/web_oauth_callback',
            ],
        ];
        $app = Factory::officialAccount($web_config);
        $oauth = $app->oauth;
        $oauth->redirect()->send();
    }

    public function web_oauth_callback()
    {
        $plugin = new  WechatPlugin();
        $config = $plugin->config();
        $web_config = [
            'app_id' => $config['web_appid'],
            'secret' => $config['web_secret'],
            'response_type' => 'array',
            'oauth' => [
                'scopes' => ['snsapi_userinfo'],
                'callback' => '/plugin/wechat/wechat/web_oauth_callback',
            ],
        ];
        $app = Factory::officialAccount($web_config);
        $oauth = $app->oauth;

        $user = $oauth->user()->toArray();
        $openid = $user['id'];
        header('Location:http://html.test2.zhicaisoft.cn?openid=' . $openid);
    }

    public static function auth_hook($server)
    {
        $server->push(function ($message) {
            switch ($message['MsgType']) {
                case 'event':
                    switch (strtolower($message['Event'])) {
                        case 'subscribe':
                            if (isset($message['EventKey'])) {
                                if ($message['EventKey'] && ($qrInfo = QrcodeService::getQrcode($message['Ticket'], 'ticket'))) {
                                    QrcodeService::scanQrcode($message['Ticket'], 'ticket');
                                    if (strtolower($qrInfo['third_type']) == 'spread') {
                                        try {
                                            $spreadUid = $qrInfo['third_id'];
                                            $uid = WechatUser::openidToUid($message['FromUserName'], 'openid');
                                            if ($spreadUid == $uid) return '自己不能推荐自己';
                                            $userInfo = User::getUserInfo($uid);
                                            if ($userInfo['spread_uid']) return '已有推荐人!';
                                            if (!User::setSpreadUid($userInfo['uid'], $spreadUid)) {
                                                $response = '绑定推荐人失败!';
                                            }
                                        } catch (\Exception $e) {
                                            $response = $e->getMessage();
                                        }
                                    }
                                }
                            }
                            break;
                        case 'unsubscribe':
                            event('WechatEventUnsubscribeBefore', [$message]);
                            break;
                        case 'scan':
                            $response = WechatReply::reply('subscribe');
                            if ($message->EventKey && ($qrInfo = QrcodeService::getQrcode($message->Ticket, 'ticket'))) {
                                QrcodeService::scanQrcode($message->Ticket, 'ticket');
                                if (strtolower($qrInfo['third_type']) == 'spread') {
                                    try {
                                        $spreadUid = $qrInfo['third_id'];
                                        $uid = WechatUser::openidToUid($message->FromUserName, 'openid');
                                        if ($spreadUid == $uid) return '自己不能推荐自己';
                                        $userInfo = User::getUserInfo($uid);
                                        if ($userInfo['spread_uid']) return '已有推荐人!';
                                        if (User::setSpreadUid($userInfo['uid'], $spreadUid)) {
                                            $response = '绑定推荐人失败!';
                                        }
                                    } catch (\Exception $e) {
                                        $response = $e->getMessage();
                                    }
                                }
                            }
                            break;
                        case 'location':
                            $response = MessageRepositories::wechatEventLocation($message);
                            break;
                        case 'click':
                            $response = WechatReply::reply($message->EventKey);
                            break;
                        case 'view':
                            $response = MessageRepositories::wechatEventView($message);
                            break;
                        case 'user_get_card':
                            // 用户领取会员卡  和  优惠券
                            $model = new \plugins\wechat\model\GetCardLogModel([
                                'openid' => $message['FromUserName'],
                                'card_id' => $message['CardId'],
                                'is_give_by_friend' => $message['IsGiveByFriend'],
                                'friend_user_name' => isset($message['FriendUserName']) ? $message['FriendUserName'] : '',
                                'user_card_code' => $message['UserCardCode'],
                                'old_user_card_code' => isset($message['OldUserCardCode']) ? $message['OldUserCardCode'] : '',
                                'IsRestoreMemberCard' => $message['IsRestoreMemberCard']
                            ]);
                            $res = $model->save();
                            break;
                        case 'submit_membercard_user_info':
                            // 会员激活信息 存数据库
                            $user_info = WechatUserModel::where('openid', $message['FromUserName'])->find();
                            $param['card_id'] = $message['CardId'];
                            $param['company_id'] = $user_info['company_id'];
                            $param['code'] = $message['UserCardCode'];
                            $result = hook('get_member_user_info', $param);
                            $model = GetCardLogModel::where(['openid' => $message['FromUserName'], 'card_id' => $message['CardId'], 'user_card_code' => $message['UserCardCode']])->find();
                            $common_field_list = $result[0]['user_info']['common_field_list'];

                            foreach ($common_field_list as $value) {
                                if ($value['name'] == 'USER_FORM_INFO_FLAG_LOCATION') {
                                    $model->location = $value['value'];
                                }
                                if ($value['name'] == 'USER_FORM_INFO_FLAG_SEX') {
                                    $model->sex = $value['value'] == '男' ? 1 : 0;
                                }
                                if ($value['name'] == 'USER_FORM_INFO_FLAG_MOBILE') {
                                    $model->mobile = $value['value'];
                                }
                                if ($value['name'] == 'USER_FORM_INFO_FLAG_BIRTHDAY') {
                                    $model->birthday = $value['value'];
                                }
                                if ($value['name'] == 'USER_FORM_INFO_FLAG_NAME') {
                                    $model->true_name = $value['value'];
                                }
                            }

                            $model->save();

                            // 营销活动开启  会员注册赠送积分
                            $card_info = MemberCardInfoModel::get(['card_id' => $message['CardId']]);

                            if ($card_info->is_activity == 1 && $card_info->score > 0) {

                                // 用户积分变更
                                $user = new WechatUserModel;
                                $user::where('id', $user_info['id'])->setInc('points', $card_info['score']);

                                // 积分日志
                                $log = new WechatUserPointsLogModel;
                                $log->data([
                                    'user_id' => $user_info['id'],
                                    'change_points' => $card_info['score'],
                                    'before_points' => $user_info['points'],
                                    'after_points' => $user_info['points'] + $card_info['score'],
                                    'create_time' => time(),
                                    'update_time' => time(),
                                    'remark' => '营销活动会员注册赠送' . $card_info['score'] . '积分',
                                ]);

                                $log->save();

                                // 变更 会员卡 积分
                                $obj = new WechatPlugin();

                                $obj->update_card_info([
                                    'company_id' => $user_info['company_id'],
                                    'user_id' => $user_info['id'],
                                    'cardId' => $message['CardId'],
                                    'code' => $message['UserCardCode'],
                                    'bonus' => $user_info['points'] + $card_info['score'],
                                ]);

                            }

                            // 推荐人推荐激活会员卡  得到  积分
                            if (!empty($user_info['parent_id'])) {
                                $points = Db::name('option')->where('option_name', 'user_card_register' . $user_info['company_id'])->value('option_value');

                                if (!empty($points)) {
                                    $find = WechatUserModel::where('id', $user_info['parent_id'])->find();
                                    // 用户积分变更
                                    $parent = new WechatUserModel;
                                    $parent::where('id', $user_info['parent_id'])->setInc('points', $points);

                                    // 积分日志
                                    $logg = new WechatUserPointsLogModel;
                                    $logg->data([
                                        'user_id' => $user_info['parent_id'],
                                        'change_points' => $points,
                                        'before_points' => $find['points'],
                                        'after_points' => $find['points'] + $points,
                                        'create_time' => time(),
                                        'update_time' => time(),
                                        'remark' => '分享用户昵称为：' . $user_info['nickname'] . '，激活会员卡成功获得' . $points . '积分',
                                    ]);
                                    if (!$logg->save()) {
                                        throw new \Exception('网络错误请稍后重试！');
                                    }
                                    // 变更 会员卡 积分
                                    $cardInfo = \api\crm\model\GetCardLogModel::where('openid', $find['openid'])
                                        ->distinct(true)
                                        ->field('card_id,user_card_code')->select();

                                    $obj = new WechatPlugin();
                                    if ($cardInfo) {
                                        foreach ($cardInfo as $k => $v) {
                                            $obj->update_card_info([
                                                'company_id' => $find['company_id'],
                                                'user_id' => $find['id'],
                                                'cardId' => $v['card_id'],
                                                'code' => $v['user_card_code'],
                                                'bonus' => $find['points'] + $points
                                            ]);
                                        }
                                    }

                                }
                            }


                            break;
                    }
                    break;
                case 'text':
                    return new Transfer();
                    break;
                case 'image':
                    return new Transfer();
//                    return '收到图片消息';
                    break;
                case 'voice':
                    return new Transfer();
//                    return '收到语音消息';
                    break;
                case 'video':
                    return new Transfer();
//                    return '收到视频消息';
                    break;
                case 'location':
                    return '收到坐标消息';
                    break;
                case 'link':
                    return new Transfer();
//                    return '收到链接消息';
                    break;
                case 'file':
                    return '收到文件消息';
                // ... 其它消息
                default:
                    $response = MessageRepositories::wechatMessageOther($message);
                    break;
            }
            return $response ? $response : false;
            // ...
        });
    }

    public static function hook($server)
    {
        $server->push(function ($message) {
            switch ($message['MsgType']) {
                case 'event':
                    switch (strtolower($message['Event'])) {
                        case 'subscribe':
                            if (isset($message['EventKey'])) {
                                if ($message['EventKey'] && ($qrInfo = QrcodeService::getQrcode($message['Ticket'], 'ticket'))) {
                                    QrcodeService::scanQrcode($message['Ticket'], 'ticket');
                                    if (strtolower($qrInfo['third_type']) == 'spread') {
                                        try {
                                            $spreadUid = $qrInfo['third_id'];
                                            $uid = WechatUser::openidToUid($message['FromUserName'], 'openid');
                                            if ($spreadUid == $uid) return '自己不能推荐自己';
                                            $userInfo = User::getUserInfo($uid);
                                            if ($userInfo['spread_uid']) return '已有推荐人!';
                                            if (!User::setSpreadUid($userInfo['uid'], $spreadUid)) {
                                                $response = '绑定推荐人失败!';
                                            }
                                        } catch (\Exception $e) {
                                            $response = $e->getMessage();
                                        }
                                    }
                                }
                            }
                            break;
                        case 'unsubscribe':
                            event('WechatEventUnsubscribeBefore', [$message]);
                            break;
                        case 'scan':
                            $response = WechatReply::reply('subscribe');
                            if ($message->EventKey && ($qrInfo = QrcodeService::getQrcode($message->Ticket, 'ticket'))) {
                                QrcodeService::scanQrcode($message->Ticket, 'ticket');
                                if (strtolower($qrInfo['third_type']) == 'spread') {
                                    try {
                                        $spreadUid = $qrInfo['third_id'];
                                        $uid = WechatUser::openidToUid($message->FromUserName, 'openid');
                                        if ($spreadUid == $uid) return '自己不能推荐自己';
                                        $userInfo = User::getUserInfo($uid);
                                        if ($userInfo['spread_uid']) return '已有推荐人!';
                                        if (User::setSpreadUid($userInfo['uid'], $spreadUid)) {
                                            $response = '绑定推荐人失败!';
                                        }
                                    } catch (\Exception $e) {
                                        $response = $e->getMessage();
                                    }
                                }
                            }
                            break;
                        case 'location':
                            $response = MessageRepositories::wechatEventLocation($message);
                            break;
                        case 'click':
                            $response = WechatReply::reply($message->EventKey);
                            break;
                        case 'view':
                            $response = MessageRepositories::wechatEventView($message);
                            break;
                        case 'user_get_card':
                            // 用户领取会员卡  和  优惠券
                            $model = new \plugins\wechat\model\GetCardLogModel([
                                'openid' => $message['FromUserName'],
                                'card_id' => $message['CardId'],
                                'is_give_by_friend' => $message['IsGiveByFriend'],
                                'friend_user_name' => isset($message['FriendUserName']) ? $message['FriendUserName'] : '',
                                'user_card_code' => $message['UserCardCode'],
                                'old_user_card_code' => isset($message['OldUserCardCode']) ? $message['OldUserCardCode'] : '',
                                'IsRestoreMemberCard' => $message['IsRestoreMemberCard']
                            ]);
                            $res = $model->save();
                            break;
                        case 'submit_membercard_user_info':
                            // 会员激活信息 存数据库
                            $user_info = WechatUserModel::where('openid', $message['FromUserName'])->find();
                            $param['card_id'] = $message['CardId'];
                            $param['company_id'] = $user_info['company_id'];
                            $param['code'] = $message['UserCardCode'];
                            $result = hook('get_member_user_info', $param);
                            $model = GetCardLogModel::where(['openid' => $message['FromUserName'], 'card_id' => $message['CardId'], 'user_card_code' => $message['UserCardCode']])->find();
                            $common_field_list = $result[0]['user_info']['common_field_list'];

                            foreach ($common_field_list as $value) {
                                if ($value['name'] == 'USER_FORM_INFO_FLAG_LOCATION') {
                                    $model->location = $value['value'];
                                }
                                if ($value['name'] == 'USER_FORM_INFO_FLAG_SEX') {
                                    $model->sex = $value['value'] == '男' ? 1 : 0;
                                }
                                if ($value['name'] == 'USER_FORM_INFO_FLAG_MOBILE') {
                                    $model->mobile = $value['value'];
                                }
                                if ($value['name'] == 'USER_FORM_INFO_FLAG_BIRTHDAY') {
                                    $model->birthday = $value['value'];
                                }
                                if ($value['name'] == 'USER_FORM_INFO_FLAG_NAME') {
                                    $model->true_name = $value['value'];
                                }
                            }

                            $model->save();

                            // 营销活动开启  会员注册赠送积分
                            $card_info = MemberCardInfoModel::get(['card_id' => $message['CardId']]);

                            if ($card_info->is_activity == 1 && $card_info->score > 0) {

                                // 用户积分变更
                                $user = new WechatUserModel;
                                $user::where('id', $user_info['id'])->setInc('points', $card_info['score']);

                                // 积分日志
                                $log = new WechatUserPointsLogModel;
                                $log->data([
                                    'user_id' => $user_info['id'],
                                    'change_points' => $card_info['score'],
                                    'before_points' => $user_info['points'],
                                    'after_points' => $user_info['points'] + $card_info['score'],
                                    'create_time' => time(),
                                    'update_time' => time(),
                                    'remark' => '营销活动会员注册赠送' . $card_info['score'] . '积分',
                                ]);

                                $log->save();

                                // 变更 会员卡 积分
                                $obj = new WechatPlugin();

                                $obj->update_card_info([
                                    'company_id' => $user_info['company_id'],
                                    'user_id' => $user_info['id'],
                                    'cardId' => $message['CardId'],
                                    'code' => $message['UserCardCode'],
                                    'bonus' => $user_info['points'] + $card_info['score'],
                                ]);

                            }

                            // 推荐人推荐激活会员卡  得到  积分
                            if (!empty($user_info['parent_id'])) {
                                $points = Db::name('option')->where('option_name', 'user_card_register' . $user_info['company_id'])->value('option_value');

                                if (!empty($points)) {
                                    $find = WechatUserModel::where('id', $user_info['parent_id'])->find();
                                    // 用户积分变更
                                    $parent = new WechatUserModel;
                                    $parent::where('id', $user_info['parent_id'])->setInc('points', $points);

                                    // 积分日志
                                    $logg = new WechatUserPointsLogModel;
                                    $logg->data([
                                        'user_id' => $user_info['parent_id'],
                                        'change_points' => $points,
                                        'before_points' => $find['points'],
                                        'after_points' => $find['points'] + $points,
                                        'create_time' => time(),
                                        'update_time' => time(),
                                        'remark' => '分享用户昵称为：' . $user_info['nickname'] . '，激活会员卡成功获得' . $points . '积分',
                                    ]);
                                    if (!$logg->save()) {
                                        throw new \Exception('网络错误请稍后重试！');
                                    }
                                    // 变更 会员卡 积分
                                    $cardInfo = \api\crm\model\GetCardLogModel::where('openid', $find['openid'])
                                        ->distinct(true)
                                        ->field('card_id,user_card_code')->select();

                                    $obj = new WechatPlugin();
                                    if ($cardInfo) {
                                        foreach ($cardInfo as $k => $v) {
                                            $obj->update_card_info([
                                                'company_id' => $find['company_id'],
                                                'user_id' => $find['id'],
                                                'cardId' => $v['card_id'],
                                                'code' => $v['user_card_code'],
                                                'bonus' => $find['points'] + $points
                                            ]);
                                        }
                                    }

                                }
                            }


                            break;
                    }
                    break;
                case 'text':
                    return new Transfer();
//                    return '收到文字消息';
                    break;
                case 'image':
                    return new Transfer();
//                    return '收到图片消息';
                    break;
                case 'voice':
                    return new Transfer();
//                    return '收到语音消息';
                    break;
                case 'video':
                    return new Transfer();
//                    return '收到视频消息';
                    break;
                case 'location':
                    return '收到坐标消息';
                    break;
                case 'link':
                    return new Transfer();
//                    return '收到链接消息';
                    break;
                case 'file':
                    return '收到文件消息';
                // ... 其它消息
                default:
                    $response = MessageRepositories::wechatMessageOther($message);
                    break;
            }
            return $response ? $response : false;
            // ...
        });
    }

    public function releaseToNetWork($open_platform, $authorizer_appid)
    {
        $message = $open_platform->server->getMessage();
        //返回API文本消息
        if ($message['MsgType'] == 'text' && strpos($message['Content'], "QUERY_AUTH_CODE:") !== false) {
            $auth_code = str_replace("QUERY_AUTH_CODE:", "", $message['Content']);
            $authorization = $open_platform->handleAuthorize($auth_code);
            $official_account_client = $open_platform->officialAccount($authorizer_appid, $authorization['authorization_info']['authorizer_refresh_token']);
            $content = $auth_code . '_from_api';
//            $official_account_client['customer_service']->send([
//                'touser' => 'gh_3c884a361561',
//                'msgtype' => 'text',
//                'text' => [
//                    'content' => $content
//                ]
//            ]);
            $replay = new Text($content);
            $official_account_client->customer_service->message($replay)->to($message['FromUserName'])->send();
            //返回普通文本消息
        } elseif ($message['MsgType'] == 'text' && $message['Content'] == 'TESTCOMPONENT_MSG_TYPE_TEXT') {
            $official_account_client = $open_platform->officialAccount($authorizer_appid);
            $content = $message['Content'] . '_callback';
//            $replay = new Text($content);
//            $official_account_client->customer_service->message($replay)->to($message['FromUserName'])->send();

            $official_account_client->server->push(function ($message) {
                return $message['Content'] . "_callback";
            });
            //发送事件消息
        } elseif ($message['MsgType'] == 'event') {
            $official_account_client = $open_platform->officialAccount($authorizer_appid);
            $official_account_client->server->push(function ($message) {
                return $message['Event'] . 'from_callback';
            });
        }
        $response = $official_account_client->server->serve();
        $response->send();
    }
}
